<?php

class Util {
  public static $configObj=null;

  public static function getConfigObj(){
    $configFile=self::getRootDirectory()."/store/env.json";

    if (!file_exists($configFile)){
      Res::error(500,'没有找到env文件: '.$configFile);
      exit();
    }

    self::$configObj=json_decode(file_get_contents($configFile),true);
    if (self::$configObj === null){
      Res::error(500,'没有设置或JSON格式错误');
      exit();
    }
  }

  public static function getRootDirectory(){
    if (substr($_SERVER['DOCUMENT_ROOT'],-1) === "\\" || substr($_SERVER['DOCUMENT_ROOT'],-1)==="/" ){
      return substr($_SERVER['DOCUMENT_ROOT'],0,-1);
    }else{
      return $_SERVER['DOCUMENT_ROOT'];
    }
  }

  public static function config($key=''){
    if (self::$configObj===null){
      self::getConfigObj();
    }

    if ($key===''){
      return self::$configObj;
    }else{
      $key=strtolower($key);
      if (isset(self::$configObj[$key])){
        return self::$configObj[$key];
      }else{
        return null;
      }
    }
  }

  public static function uuid(){
    $strArr=explode(",","a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i,9,j,0,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z");
    $uuidStr="";
    for ($i=0;$i<36;$i++){
        $uuidStr.=$strArr[mt_rand(0,35)];
    }
    $uuidStr[8]=$uuidStr[13]=$uuidStr[18]=$uuidStr[23]="-";
    return $uuidStr;
  }

  public static function proxy($options){
    $options[CURLOPT_FAILONERROR]=true;
    $ch=curl_init();
    curl_setopt_array($ch,$options);
    $txt=curl_exec($ch);
    curl_close($ch);
    return $txt;
  }
}